<template>
  <div class="mod-fina-details">
    <!-- 财务明细 -->
    <!-- 标题 -->
    <div class="header">
      <h3>{{$t('finaManage.finaDeta')}}</h3>
    </div>
    <!-- end -->

    <!-- 条件查询选项框 -->
    <div class="query">
      <div class="query-box">
        <!-- 时间选区，筛选 -->
        <div class="query-selects">
          <!-- 导出报表 -->
          <span class="inline-span">
            <el-button size="mini">
              <a v-on:click="exportFrom()">{{$t('order.exportForm')}}</a>
            </el-button>
          </span>
          <!-- 门店选择-->
          <span class="inline-span">
            <el-select v-model="storeId" style="width:100px;height: 15px;" size="mini">
              <el-option
                v-for="item in dropDowmOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </span>
          <!-- 时间框选择 -->
          <span class="inline-span">
            <span>{{$t('finaManage.transactionHour')}}：</span>
            <span class="time">
              <el-select
                v-model="dateValue"
                @change="setDateRange(dateValue)"
                style="width:100px;height: 15px;"
                size="mini"
              >
                <el-option
                  v-for="item in dateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <span
                class="title-time"
                v-if="dateValue === 1 || dateValue === 2 "
              >{{startTime}} {{$t('date.tip')}} {{endTime}}</span>
              <span class="title-time title-time-span" v-if="dateValue === 3">
                <el-date-picker
                  class="title-time-Range"
                  v-model="dateRangeParam"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="-"
                  :start-placeholder="$t('date.start')"
                  :end-placeholder="$t('date.end')"
                  value-format="timestamp"
                >></el-date-picker>
              </span>
            </span>
          </span>
          <!-- 单号查询 -->
          <span class="inline-span">
            <el-select v-model="oddValue" style="width:110px;height: 15px;" size="mini">
              <el-option
                v-for="item in oddNumbers"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </span>
          <span class="inline-span">
            <el-input v-model="orderId" :placeholder="$t('finaManage.pleEntOrderNum')" class="odd-input"></el-input>
          </span>
          <!-- 查询清空按钮 -->
          <span class="inline-span butt">
            <el-button type="primary" v-on:click="getFinaDetailsData" plain icon="el-icon-search">{{$t('order.query')}}</el-button>
            <el-button icon="el-icon-delete" v-on:click="resetData">{{$t('order.clear')}}</el-button>
          </span>
        </div>
        <!-- end -->

        <!-- 单选区 -->
        <div>
          <span class="text" style="margin-left:6px;
          line-height:40px">{{$t('finaManage.filtCondi')}}</span>
          <span>
            <el-switch v-model="isFilter" active-color="#86c9f9" inactive-color="#e4e4e4"></el-switch>
          </span>
        </div>
        <!-- 选择区域展示与选择 -->
        <div class="option-box" v-if="isFilter">
          <div class="block money">
            <span class="text">{{$t('finaManage.amountTrans')}}</span>
            <span>
              <el-input
                oninput="value=value.replace(/[^0-9.]/g,'')"
                class="money-input" type="number" v-model="minAmount" :placeholder="$t('withdraw.unlimited')"></el-input>
              <span>——</span>
              <el-input
                oninput="value=value.replace(/[^0-9.]/g,'')"
                class="money-input" type="number" v-model="maxAmount" :placeholder="$t('withdraw.unlimited')"></el-input>
            </span>
          </div>

          <div class="block type">
            <span class="text">{{$t('shop.ioType')}}</span>
            <span>
              <el-radio v-model="incPayType" :label="0" border size="small">{{$t('seckill.unlimited')}}</el-radio>
              <el-radio v-model="incPayType" :label="1" border size="small">{{$t('shop.income')}}</el-radio>
              <el-radio v-model="incPayType" :label="2" border size="small">{{$t('shop.pay')}}</el-radio>
            </span>
          </div>
          <div class="block mode">
            <span class="text">{{$t('order.paymentMethod')}}</span>
            <span>
              <el-radio v-model="payType" :label="-1" border size="small">{{$t('seckill.unlimited')}}</el-radio>
              <el-radio v-model="payType" v-for="(item,index) in payTypeList" :key="index" :label="index" border size="small">{{item}}</el-radio>
            </span>
          </div>
        </div>
      </div>
    </div>
    <!-- end -->

    <!-- 查询数据展示表 -->
    <div class="query dataSheet">
      <div>
        <el-table :data="tableData" style="width: 99%">
          <el-table-column prop="transDate" :label="$t('finaManage.transactionHour')" :render-header="renderHeadeTime"></el-table-column>
          <el-table-column prop="orderId" :label="$t('order.number')" :render-header="renderHeadeThree"></el-table-column>
          <el-table-column prop="incPayType" :label="$t('shop.ioType')"></el-table-column>
          <el-table-column prop="payType" :label="$t('order.paymentMethod')"></el-table-column>
          <el-table-column prop="transAmount" :label="$t('finaManage.amountTrans')"></el-table-column>
        </el-table>
        <el-pagination
          class="paging"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal"
        ></el-pagination>
      </div>
    </div>
    <!-- end -->
  </div>
</template>

<script>
  import moment from 'moment'
  export default {
    data () {
      return {
        storeId: -1,  // 门店切换数据
        dropDowmOptions: [
          {
            label: this.$i18n.t('date.a'),
            value: -1
          }
        ],
        oddValue: '1',  // 单号查询数据
        oddNumbers: [
          {
            label: this.$i18n.t('order.number'),
            value: '1'
          }
        ],
        orderId: '',  // 单号输入

        dateRange: [], // 展示的时间参数
        dateRangeParam: [],
        timeRange: '',
        startTime: '',
        endTime: '',
        dateValue: 1, //  时间栏默认选中
        dateOptions: [
          {
            label: this.$i18n.t('user.lastSevenDay'),
            value: 1
          },
          {
            label: this.$i18n.t('user.lastThirtyDay'),
            value: 2
          },
          {
            label: this.$i18n.t('user.customRange'),
            value: 3
          }
        ],
        isFilter: false, //  筛选按钮判断
        finaData: '', //  财务数据

        incPayType: 0,  //  筛选条件
        radio2: '1',
        radio3: '1',
        radio4: '1',
        payType: -1, // 当前选中的支付方式 -1表示不限
        payTypeList: [this.$i18n.t('order.pointsPayment'), this.$i18n.t('platform.weChatPay'), this.$i18n.t('platform.aliPay'), this.$i18n.t('order.wechatScanCodePayment'), this.$i18n.t('order.wechatH5Payment'), this.$i18n.t('order.weclAccountPay'), this.$i18n.t('order.alipayH5Payment'), this.$i18n.t('order.alipayAPPPayment'), this.$i18n.t('order.wechatAPPPayment'), this.$i18n.t('order.balancePayment'), this.$i18n.t('order.payPalPayment')], // 所有支付方式
        minAmount: null, // 交易金额
        maxAmount: null,

        tableData: [
          { transDate: null, orderId: null, incPayType: null, payType: null, transAmount: null }
        ],  //  表格数据

        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
        pageTotal: 0, // 一共多少条数据

        tempFormData: null
      }
    },
    watch: {
      /**
       * 关闭筛选则修改为默认值
       */
      isFilter (val) {
        if (!val) {
          this.incPayType = 0
          this.minAmount = null
          this.maxAmount = null
          this.payType = -1
        }
      },
      dateRangeParam: {
        handler (newValue, oldValue) {
          this.getFinaDetailsData()
        },
        deep: true
      },
      storeId (val) {
        this.getFinaDetailsData()
      }
    },
    mounted () {
      this.getShopList()
      this.setDateRange(1)
    },
    methods: {
      // 点击查询
      getFinaDetailsData () {
        this.currentPage = 1
        this.tempFormData = Object.assign({
          start: this.dateRangeParam[0],
          end: this.dateRangeParam[1],
          stationId: this.storeId,
          orderId: this.orderId,
          payType: this.payType,
          incPayType: this.incPayType,
          minAmount: this.minAmount,
          maxAmount: this.maxAmount,
          current: this.currentPage,
          size: this.pageSize
        })
        this.$http({
          url: this.$http.adornUrl('/platform/financialManagement/getFinanDetail'),
          method: 'get',
          params: this.$http.adornParams({
            start: this.dateRangeParam[0],
            end: this.dateRangeParam[1],
            stationId: this.storeId,
            orderId: this.orderId,
            payType: this.payType,
            incPayType: this.incPayType,
            minAmount: this.minAmount,
            maxAmount: this.maxAmount,
            current: this.currentPage,
            size: this.pageSize
          })
        }).then(({ data }) => {
          // console.log(data)
          this.tableData = data.records
          // 将支付类型（int）转中文（str）
          this.tableData.forEach(element => {
            element.payType = this.payTypeList[element.payType]
            if (element.incPayType === '1') {
              element.incPayType = this.$i18n.t('shop.income')
            } else {
              element.incPayType = this.$i18n.t('shop.pay')
            }
          })
          this.currentPage = data.current
          this.pageSize = data.size
          this.pageTotal = data.total
        })
      },
      // 页数查询
      getFinaDataByCurrPage () {
        this.$http({
          url: this.$http.adornUrl('/platform/financialManagement/getFinanDetail'),
          method: 'get',
          params: this.$http.adornParams({
            start: this.tempFormData.start,
            end: this.tempFormData.end,
            stationId: this.tempFormData.stationId,
            orderId: this.tempFormData.orderId,
            payType: this.tempFormData.payType,
            incPayType: this.tempFormData.incPayType,
            minAmount: this.tempFormData.minAmount,
            maxAmount: this.tempFormData.maxAmount,
            current: this.tempFormData.current,
            size: this.tempFormData.size
          })
        }).then(({ data }) => {
          // console.log(data)
          this.tableData = data.records
          // 将支付类型（int）转中文（str）
          this.tableData.forEach(element => {
            element.payType = this.payTypeList[element.payType]
            if (element.incPayType === '1') {
              element.incPayType = this.$i18n.t('shop.income')
            } else {
              element.incPayType = this.$i18n.t('shop.pay')
            }
          })
          this.currentPage = data.current
          this.pageSize = data.size
          this.pageTotal = data.total
        })
      },
      // 清空
      resetData () {
        this.orderId = null
        this.payType = -1
        this.incPayType = 0
        this.maxAmount = null
        this.minAmount = null
      },

      exportFrom () {
        this.$http({
          url: this.$http.adornUrl('/platform/financialManagement/getFinanDetailForm'),
          method: 'get',
          params: this.$http.adornParams({
            start: this.tempFormData.start,
            end: this.tempFormData.end,
            stationId: this.tempFormData.stationId,
            orderId: this.tempFormData.orderId,
            payType: this.payType,
            incPayType: this.incPayType,
            minAmount: this.minAmount,
            maxAmount: this.maxAmount
          }),
          responseType: 'blob'
        }).then(({ data }) => {
          var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
          const fileName = this.$i18n.t('finaManage.finaDeta') +
            '(' + moment(this.tempFormData.start).format('yyyy-MM-DD') +
            ' ' + this.$i18n.t('date.tip') + ' ' +
            moment(this.tempFormData.end).format('yyyy-MM-DD') + ').xls'

          const elink = document.createElement('a')
          if ('download' in elink) { // 非IE下载
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
      },
      // 1-3:最近7天、最近30天、自定义时间
      setDateRange (val) {
        var startDay = null
        var endDay = null
        this.dateValue = val
        if (val === 1) {
          startDay = -7
          endDay = -1
        } else if (val === 2) {
          startDay = -30
          endDay = -1
        } else if (val === 3) {
          startDay = -2
          endDay = 0
        } else {
          return
        }
        // 开始时间
        let startTime = moment().add(startDay, 'days').startOf('days')

        // 结束时间
        let endTime = moment().add(endDay, 'days').endOf('days')
        this.startTime = startTime.format('L')
        this.endTime = endTime.format('L')
        this.dateRange = [this.startTime, this.endTime]
        this.dateRangeParam = [moment(this.startTime).unix() * 1000, moment(this.endTime).unix() * 1000]
      },
      // 为表格头标题添加小图标并hover后出现提示信息
      renderHeadeTime (h, { column, $index }) {
        // h 是一个渲染函数       column 是一个对象表示当前列      $index 第几列
        return h('div', [
          h('span', column.label + '  ', {
            align: 'center'
          }),
          h(
            'el-popover',
            {
              props: {
                placement: 'top',    // 一般 icon 处可添加浮层说明，浮层位置等属性
                width: '240',
                trigger: 'hover'
              }
            },
            [
              h('p', this.$i18n.t('finaManage.succOrFailTime'), {
                class: 'text-align: center; margin: 0'
              }),
              h('i', {                            // 生成 i 标签 ，添加icon 设置 样式，slot 必填
                class: 'el-icon-question',
                style: 'color:#ccc,margin:18px',
                slot: 'reference'
              })
            ]
          )
        ])
      },
      renderHeadeThree (h, { column, $index }) {
        return h('div', [
          h('span', column.label + '  ', {
            align: 'center'
          }),
          h(
            'el-popover',
            {
              props: {
                placement: 'top',
                width: '240',
                trigger: 'hover'
              }
            },
            [
              h('p', this.$i18n.t('finaManage.twoOrderNum'), {
                class: 'text-align: center; margin: 0'
              }),
              h('i', {
                class: 'el-icon-question',
                style: 'color:#ccc,margin:18px',
                slot: 'reference'
              })
            ]
          )
        ])
      },
      // 页数的切换
      handleSizeChange (val) {
        this.pageSize = val
        this.tempFormData.size = val
        this.getFinaDataByCurrPage()
      },
      //  换页
      handleCurrentChange (val) {
        this.currentPage = val
        this.tempFormData.current = val
        // this.tempFormData.size
        this.getFinaDataByCurrPage()
      },
      getShopList () {
        this.$http({
          url: this.$http.adornUrl(`/platform/financialManagement/getStation`),
          method: 'get',
          params: this.$http.adornParams({
            shopId: null
          })
        }).then(({data}) => {
          if (data) {
            for (let i = 0; i < data.length; i++) {
              this.dropDowmOptions.push({
                label: data[i].stationName,
                value: data[i].stationId
              })
            }
            // this.dropDowmOptions.push({
            //   label: this.$i18n.t('prodList.other'),
            //   value: -2
            // })
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .mod-fina-details {
    a {
      text-decoration: none;
    }

    .el-radio {
      margin-right: 0;
      margin-bottom: 10px;
    }

    .el-table .cell {
      line-height: 16px;
    }

    .header {
      margin: 10px 0;
      margin-bottom: 28px;
    }

    .header h3 {
      color: #4d4d4d;
      font-weight: 580;
    }

    // 时间选框的设定
    .title-time {
      padding-left: 8px;
      color: #8f8f8f;
      border-radius: 6px;
    }

    .title-time-span {
      .el-date-editor .el-range__icon {
        line-height: 22px;
      }

      .el-date-editor .el-range-separator {
        width: 6%;
        line-height: 24px;
      }

      .el-date-editor .el-range__close-icon {
        line-height: 24px;
      }
    }

    .title-time-Range {
      height: 30px;
    }

    // 查询部分
    .query {
      // height: 180px;
      margin: 10px 0;
      background-color: #f8f8f8;
      padding-left: 10px;
      padding-bottom: 10px;
      border-radius: 6px;
    }

    .query-selects {
      padding: 20px 0;
    }

    .query-box .text {
      padding-right: 30px;
    }

    .option-box .block {
      margin: 14px 6px;
    }

    .odd-input {
      display: inline-block;
      width: 180px;
      margin-left: -20px;
    }

    .odd-input .el-input__inner {
      height: 28px !important;
    }

    .query-selects {
      position: relative;
    }

    .query-selects .inline-span {
      margin-right: 16px;
    }

    .query-selects .butt {
      line-height: 50px;
    }

    // 表格部分
    .dataSheet {
      // height: 600px;
      padding-top: 20px;
    }

    .dataSheet .paging {
      padding-top: 20px;
      padding-right: 20px;
    }

    .money-input {
      display: inline-block;
      width: 140px;
    }

    .money-input .el-input__inner {
      height: 36px !important;
    }
  }
</style>

